import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import App from './App'
import Home from './pages/Home'
import About from './pages/About'
import './index.css'

let root = null

// 渲染函数
function render(props = {}) {
  const { container, name } = props
  const baseUrl = window.__POWERED_BY_QIANKUN__ ? `/${name}` : ''
  
  const rootElement = container 
    ? container.querySelector('#root') 
    : document.getElementById('root')
  
  root = ReactDOM.createRoot(rootElement)
  
  root.render(
    <React.StrictMode>
      <BrowserRouter basename={baseUrl}>
        <App>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
          </Routes>
        </App>
      </BrowserRouter>
    </React.StrictMode>
  )
}

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  render()
}

// 导出乾坤生命周期钩子
export async function bootstrap() {
  console.log('react app bootstraped')
}

export async function mount(props) {
  console.log('react app mounted', props)
  render(props)
}

export async function unmount() {
  console.log('react app unmounted')
  if (root) {
    root.unmount()
    root = null
  }
}